<?php

namespace app\admin\controller\xiluedu;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{
    protected $noNeedRight=['selectpage'];
    /**
     * Category模型对象
     * @var \app\admin\model\xiluedu\Category
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xiluedu\Category;
        $this->view->assign("defaultStatusList", $this->model->getDefaultStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());

        // 必须将结果集转换为数组
        $categoryList = collection($this->model->order('weigh', 'desc')->order('id', 'asc')->select())->toArray();
        Tree::instance()->init($categoryList);
        $this->categoryList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $categoryData = [0 => __('None')];
        foreach ($this->categoryList as $k => &$v) {
            $categoryData[$v['id']] = $v['name'];
        }
        unset($v);
        $this->view->assign('categoryData', $categoryData);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $list = $this->categoryList;
            $total = count($this->categoryList);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('choose',input('choose',false));
        return $this->view->fetch();
    }

    public function add() {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                $result = $this->model->save($params);
                if ($result === false) {
                    Db::rollback();
                    $this->error($this->model->getError());
                }
                if($this->model->pid) {
                    $pModel = \app\admin\model\xiluedu\Category::get($this->model->pid);
                    $this->model->save([
                        'path'=>$pModel->path.$this->model->id.',',
                        'name_path'=>$pModel->name_path.$this->model->name.','
                    ]);
                }else {
                    $this->model->save([
                        'path'=>$this->model->id.',',
                        'name_path'=>$this->model->name.','
                    ]);
                }
                Db::commit();
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->getChildrenIds($row['id']);
                    $childrenIds[] = $row['id'];
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('父级别不能是它的子级别'));
                    }
                }
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $oldPath = $row->path;
                $oldNamePath = $row->name_path;
                if($row->pid) {
                    $pModel = \app\admin\model\xiluedu\Category::get($row->pid);
                    $row->save([
                        'path'=>$pModel->path.$row->id.',',
                        'name_path'=>$pModel->name_path.$row->name.','
                    ]);
                }else {
                    $row->save([
                        'path'=>$row->id.',',
                        'name_path'=>$row->name.','
                    ]);
                }
                $newPath = $row->path;
                $newNamePath = $row->name_path;
                if($oldPath!=$newPath) {
                    // 更新当前节点所有子节点path, 通过修改前的path查找
                    $nodes = \app\admin\model\xiluedu\Category::where('path', 'like', $oldPath . '%')
                        ->order('path', 'asc')
                        ->update([
                            'path' => Db::raw("replace(path,'$oldPath','$newPath')"),
                            'name_path' => Db::raw("replace(name_path,'$oldNamePath','$newNamePath')"),
                        ]);
                }

                //全量更新的代码
//                $nodes = \app\common\model\JobCategory::where('pid', '<>','0')
//                    ->order('path', 'asc')
//                    ->select();
//                foreach ($nodes as $node) {
//                    $parent = \app\common\model\JobCategory::where('id', $node->pid)->find();
//                    $node->save([
//                        'path' => $parent->path . $node->id . ',',
//                        'name_path'=>$parent->name_path.$node->category_name.','
//                    ]);
//                }
                Db::commit();
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function selectpage()
    {
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }
}
